import { Injectable } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { Observable, of } from 'rxjs';
import { map} from 'rxjs/operators';

@Injectable()
export class AreaService {
  cacheArea = [];
  cacheProvince = [];
  cacheAll=[];
  loading  = true;
  constructor(private  apiService:ApiService) {
    this.apiService.post("mas.area.findAll",{}).pipe(map( body=>{
      this.cacheAll = body;
      this.cacheProvince=this.cacheAll.filter(item => !item.hasOwnProperty("parent"))
    }
    )).subscribe();
  }


  getOption(param):Observable<any> {
    if (this.cacheAll.filter(item=> item.id==param.id).length ==0){
      return this.apiService.post("mas.area.findOne", param).pipe(map(
        (body) => {
          if ( body ) {
            return  body;
          }
        }));
    }
    return of(this.cacheAll.filter(item=> item.id==param.id)[0]);
  }

  getProvince():Observable<any> {
    if (this.cacheProvince.length == 0 ){
      const data = {};
      return this.apiService.post("mas.area.findProvince", data).pipe(map(
        (body) => {
          if ( body ) {
            this.cacheProvince =  body;
            return  body;
          }
        }));
    }else{
      return of(this.cacheProvince);
    }
  }

  getChildren(param:any):Observable<any>{
    let key = param.id;
    if  (this.cacheArea[key]==undefined){
      this.cacheArea[key]=this.cacheAll.filter(item=> item.parent==param.id);
    }
    return of(this.cacheArea[key]);

  }

}
